package cn.hg.solon.youcan.framework.task;

import java.util.Date;
import java.util.List;

import org.dromara.hutool.core.date.DateUtil;
import org.dromara.hutool.core.util.ObjUtil;
import org.noear.solon.annotation.Component;
import org.noear.solon.annotation.Inject;

import cn.dev33.satoken.session.SaSession;
import cn.dev33.satoken.stp.StpUtil;
import cn.hg.solon.youcan.common.constant.OnlineConstants;
import cn.hg.solon.youcan.common.enums.OnlineStatus;
import cn.hg.solon.youcan.system.entity.UserOnline;
import cn.hg.solon.youcan.system.service.UserOnlineService;

/**
 * @author 胡高
 */
@Component(name = "usrOnlineTask")
public class UserOnlineTask {

    @Inject
    UserOnlineService userOnlineService;

    private void doOfflines() {
        Date now = DateUtil.now();

        List<? extends UserOnline> onlineList = this.userOnlineService.onlineList();

        for (UserOnline online : onlineList) {
            SaSession session = StpUtil.getTokenSessionByToken(online.getId());
            if (ObjUtil.isNotNull(session)) {
                Date expDate = (Date) session.get(OnlineConstants.EXPIRATION_DATETIME);
                if (ObjUtil.isNotNull(expDate) && DateUtil.compare(now, expDate) < 0) {
                    continue;
                }
            }
            online.setStatus(OnlineStatus.OFF.name());
            this.userOnlineService.update(online);
        }
    }

    public void processOfflines() {
        this.doOfflines();
    }
}
